# 导入pptx包
from pptx import Presentation
import os

# 修改为新的PPT文件路径
ppt_path = r'.\PPTX_Sort\爬虫实训第一课.pptx'
prs = Presentation(ppt_path)

text_number = 0

# 创建输出文本文件，修改为你希望的路径
with open('.\PPTX_Sort\ppt文本.txt', 'w', encoding='utf-8-sig') as file:
    # 遍历演示文稿中的幻灯片对象
    for slide in prs.slides:
        text_number += 1
        file.writelines(['幻灯片{}'.format(text_number), '\n'])

        # 遍历幻灯片中的形状对象
        for shape in slide.shapes:
            try:
                # 获取二进制字符流
                imdata = shape.image.blob
                # 判断文件后缀类型
                imagetype = shape.image.content_type
                typekey = imagetype.find('/') + 1
                imtype = imagetype[typekey:]

                # 创建image文件夹保存提取的图片，路径修改为PPTX_Sort下
                path = os.path.join(os.path.dirname(ppt_path), "image", "幻灯片{}".format(text_number))
                if not os.path.exists(path):
                    os.makedirs(path)

                # 生成图片文件
                image_file = os.path.join(path, shape.name + "." + imtype)
                with open(image_file, 'wb') as file_str:
                    file_str.write(imdata)

            except Exception as e:
                # 判断形状对象是否包含文本
                if not shape.has_text_frame:
                    continue

                # 遍历该形状对象，获取文字
                for paragraph in shape.text_frame.paragraphs:
                    for run in paragraph.runs:
                        file.writelines([2 * '\t', run.text, '\n'])